package com.chatim.nonamechatim.netty.handler;

import com.alibaba.fastjson2.JSON;
import com.chatim.nonamechatim.mapper.MessageMapper;
import com.chatim.nonamechatim.netty.MessageType;
import com.chatim.nonamechatim.netty.common.ChatMessage;
import com.chatim.nonamechatim.netty.common.Command;
import com.chatim.nonamechatim.netty.common.WSRes;
import com.chatim.nonamechatim.pojo.Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import static com.chatim.nonamechatim.netty.ServerBoot.USERLIST;

@Component
public class ChatHandler {

    @Resource
    MessageMapper messageMapper;

    public static ChatHandler chatHandler;

    @PostConstruct
    public void init() {
        chatHandler = this;
    }

    public void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
        Command chat = JSON.parseObject(frame.text(), Command.class);
        ChatMessage msg = chat.getChatMessage();
        switch (MessageType.match(chat.getChatMessage().getType())) {
            case PRIVATE -> {
                if(!USERLIST.containsKey(msg.getTid())) {
                    ctx.channel().writeAndFlush(WSRes.fail("消息发送没有指定接收对象"));
                }
                Channel channel = USERLIST.get(msg.getTid());
                if(null == channel || !channel.isActive()){
                    // 剔除掉map中的用户数据
                    USERLIST.remove(msg.getTid());
                    // 离线处理，先保存到数据库，用户上线去数据库中取
                    Message message = new Message();
                    message.setFid(chat.getFid());
                    message.setTid(msg.getTid());
                    message.setContext(msg.getContext());
                    message.setStatus(0);
                    messageMapper.insert(message);
                } else {
                    channel.writeAndFlush(WSRes.success(chat.getFid(), msg.getContext(), msg.getTime()));
                }
            }
            default -> {
            }
        }
    }
}
